/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.web;

import com.yunqian.common.CurrentUser;
import com.yunqian.constant.RedDotKey;
import com.yunqian.exception.ActionException;
import com.yunqian.jwt.JwtUser;
import com.yunqian.redot.domain.CoursesOrder;
import com.yunqian.redot.domain.SwiftpassPay;
import com.yunqian.redot.service.CoursesOrderService;
import com.yunqian.redot.service.SwiftpassPayService;
import com.yunqian.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;


/**
 * Describe: 客户课程报名记录控制器
 *
 * @author zsy
 * 2018-09-29 15:54:11
 */
 @RestController
 @RequestMapping("/api/coursesOrder")
public class CoursesOrderController {

     @Autowired
     private CoursesOrderService coursesOrderService;
     @Autowired
     private SwiftpassPayService swiftpassPayService;

    /**
     * 获取分页
     *
     * @param params
     * @return
     */
    @PostMapping("/pagination")
    public Page<CoursesOrder> pagination(@RequestBody Map<String, Object> params, @CurrentUser JwtUser user) {
        params.put("_filter_eq_customerId", user.getId());
        return coursesOrderService.pagination(params);
    }

    /**
     * 报名
     *
     * @param coursesOrder 对象信息
     */
    @PostMapping
    public Map<String, String> save(@RequestBody @Valid CoursesOrder coursesOrder, HttpServletRequest request, @CurrentUser JwtUser user) {
        boolean exist = coursesOrderService.existsByCustomerIdAndCourseId(user.getId(), coursesOrder.getCourseId());
        if(exist){
            throw new ActionException("您已报名该课程，请勿重复报名");
        }
        coursesOrder.setCustomerId(user.getId());
        return coursesOrderService.saveOrder(coursesOrder, user.getOpenId(), HttpUtil.getIpAddress(request));
    }

    /**
     * 订单详情
     *
     * @param id 要查询的id
     * @return
     */
    @GetMapping("/{id}")
    public CoursesOrder detail(@PathVariable("id") Long id) {
        return coursesOrderService.findStrictOne(id);
    }

    /**
     * 重新支付
     * @param orderId
     * @return
     */
    @GetMapping("/pay/anew/{orderId}")
    public Map<String,String> anewPay(@PathVariable("orderId") Long orderId){
        CoursesOrder order = coursesOrderService.getById(orderId);
        Map<String,String> map = new HashMap<>(16);
        SwiftpassPay pay = swiftpassPayService.getByOutTradeNo(order.getOrderNo());
        map.put("timeStamp", pay.getTimeStamp());
        map.put("package", pay.getPrepayId());
        map.put("paySign", pay.getPaySign());
        map.put("orderId", orderId.toString());
        map.put("appId", RedDotKey.APP_ID);
        map.put("signType", "RSA");
        map.put("nonceStr",pay.getNonceStr());
        return map;
    }

}
